﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Management;
using System.Text;

/* ********************************************** 
 * Rainsoft Development Library for Microsoft.NET *  
 * *  Copyright (c) 2004,2005 RainTrail Studio.China 
 * *  All Rigths Reserved! 
 * *  Author: Q.yuhen (qyuhen@hotmail.com) 
 * ********************************************** 
 */

namespace TSharp.Core.Env
{

    #region WMIPath

    #endregion

    /// <summary> 
    /// 获取系统信息  
    /// </summary>   
    /// <example>
    /// <code>
    /// WMI w = new WMI(WMIPath.Win32_NetworkAdapterConfiguration);  
    /// for (int i = 0; i &lt; w.Count; i ++)  
    ///{  
    ///    if ((bool)w[i, "IPEnabled"])  
    ///   {  
    ///      Console.WriteLine("Caption:{0}", w[i, "Caption"]);  
    ///      Console.WriteLine("MAC Address:{0}", w[i, "MACAddress"]);  
    ///    }  
    /// }  
    /// </code>
    /// </example>
    public sealed class WMI
    {
        private readonly ArrayList mocs;
        private readonly StringDictionary names;

        /// <summary>   
        /// 构造函数   
        /// </summary>   
        /// <param name="path"></param>
        public WMI(string path)
        {
            names = new StringDictionary();
            mocs = new ArrayList();
            try
            {
                using (var cimobject = new ManagementClass(path))
                {
                    using (ManagementObjectCollection moc = cimobject.GetInstances())
                    {
                        bool ok = false;
                        foreach (ManagementObject mo in moc)
                        {
                            using (mo)
                            {
                                var o = new Hashtable();
                                mocs.Add(o);
                                foreach (PropertyData p in mo.Properties)
                                {
                                    o.Add(p.Name, p.Value);
                                    if (!ok) names.Add(p.Name.ToLower(), p.Name);
                                }
                                ok = true;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 构造函数   
        /// </summary>
        /// <param name="path"></param>
        public WMI(WMIPath path)
            : this(path.ToString())
        {
        }

        // 用来存储属性名，便于忽略大小写查询正确名称。 
        /// <summary>    
        /// 信息集合数量    
        /// </summary>    
        public int Count
        {
            get { return mocs.Count; }
        }

        /// <summary>   
        /// 获取指定属性值，注意某些结果可能是数组。    
        /// </summary>    
        public object this[int index, string propertyName]
        {
            get
            {
                try
                {
                    string trueName = names[propertyName.Trim().ToLower()];
                    // 以此可不区分大小写获得正确的属性名称。        
                    var h = (Hashtable) mocs[index];
                    return h[trueName];
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// Tries the get value.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="fun">The fun.</param>
        /// <returns></returns>
        public object TryGetValue(string propertyName, Func<Hashtable, bool> fun)
        {
            for (int i = 0, n = Count; i < n; i++)
            {
                var h = (Hashtable) mocs[i];
                if (fun(h))
                {
                    string trueName = names[propertyName.Trim().ToLower()];
                    return h[trueName];
                }
            }
            return null;
        }

        /// <summary>
        /// 返回所有属性名称。    
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public string[] PropertyNames(int index)
        {
            try
            {
                var h = (Hashtable) mocs[index];
                var result = new string[h.Keys.Count];
                h.Keys.CopyTo(result, 0);
                Array.Sort(result);
                return result;
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 返回测试信息。  
        /// </summary>
        /// <returns></returns>
        public string Test()
        {
            try
            {
                var result = new StringBuilder(1000);
                result.AppendLine("======WMI=======");
                result.AppendLine();
                for (int i = 0; i < Count; i++)
                {
                    int j = 0;
                    foreach (string s in PropertyNames(i))
                    {
                        result.Append(string.Format("{0}:{1}={2}\n", ++j, s, this[i, s]));
                        if (this[i, s] is Array)
                        {
                            var v1 = this[i, s] as Array;
                            for (int x = 0; x < v1.Length; x++)
                            {
                                result.Append("\t" + v1.GetValue(x) + "\n");
                            }
                        }
                    }
                }
                return result.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}